/* 
    绘制矩形范围,截图保存到本地
 */
import VectorSource from "ol/source/Vector";
import Draw, { createBox } from "ol/interaction/Draw";
import { Fill, Stroke, Style } from "ol/style";
import dataConfig from "./data";

export default class echartCluster {
	constructor(ol) {
		this.ol = ol;
		this._echarts = "";
		this._container = null;
		this.zIndex = 999;
	}
	init(echarts) {
		// console.log("211", echarts);
		this._echarts = echarts;
		// this._ecOptions = ecOptions;
		//保证地图渲染完成才执行专题图渲染，且只执行一次
		this.ol.once("postrender", this._render.bind(this));
		// console.log("dataConfig", dataConfig);
		this.loadData();
	}
	_render() {
		if (!this._container) {
			this._createLayerContainer();
		}
		if (!this._ec) {
			this._ec = this._echarts.init(this._container);
			this._prepareECharts();
			this._ec.setOption(this._ecOptions, false);
		} else if (this._container && this._container.style.display === "") {
			this._ec.resize();
		}
		this._bindEvent();
	}

	_bindEvent() {
		this.event = this._moveHandler("onMoveEnd");
		this.ol.on("postrender", this.event);
		this.ol.getView().on("change:resolution", this.event);
	}

	_moveHandler(type) {
		var _this = this;
		console.log("_this", _this);
		return _this[type].bind(this);
	}
	_createLayerContainer() {
		var size = this.ol.getSize();

		const dom = document.getElementById("map");

		var container = (this._container = document.createElement("div"));
		container.className = "e_container";
		container.style.height = size[1] + "px";
		container.style.width = size[0] + "px";
		container.style.top = "0px";
		container.style.left = "0px";
		container.style.zIndex = 99999;

		if (this._zIndex) {
			container.style.zIndex = this._zIndex;
		}
		this._resetContainer();
		this.ol.getViewport().appendChild(this._container);
	}

	_resetContainer() {
		var size = this.ol.getSize();

		this._container.style.width = size.width + "px";
		this._container.style.height = size.height + "px";
	}

	_prepareECharts() {
		if (!this._registered) {
			this._echarts.registerCoordinateSystem(
				"openlayers",
				this._getE3CoordinateSystem(this.ol)
			);
			this._registered = true;
		}
		var series = this._ecOptions.series;
		console.log("series", series);
		if (series) {
			for (var i = series.length - 1; i >= 0; i--) {
				series[i]["coordinateSystem"] = "openlayers";

				series[i]["animation"] = false;
			}
		}
	}

	_getE3CoordinateSystem(map) {
		var CoordSystem = function CoordSystem(map) {
			this.map = map;
			this._mapOffset = [0, 0];
		};

		CoordSystem.create = function (ecModel) {
			ecModel.eachSeries(function (seriesModel) {
				if (seriesModel.get("coordinateSystem") === "openlayers") {
					seriesModel.coordinateSystem = new CoordSystem(map);
				}
			});
		};

		CoordSystem.getDimensionsInfo = function () {
			return ["x", "y"];
		};

		CoordSystem.dimensions = ["x", "y"];

		CoordSystem.prototype.dimensions = ["x", "y"];
		CoordSystem.prototype.setMapOffset = function setMapOffset(mapOffset) {
			this._mapOffset = mapOffset;
		};
		(CoordSystem.prototype.dataToPoint = function dataToPoint(data) {
			//地理坐标转为屏幕坐标
			//console.log(data);
			var px = map.getPixelFromCoordinate(data);
			var mapOffset = this._mapOffset;
			return [px[0] - mapOffset[0], px[1] - mapOffset[1]];
		}),
			(CoordSystem.prototype.pointToData = function pointToData(pt) {
				//屏幕坐标转为地理坐标
				var mapOffset = this._mapOffset;
				var data = map.containerPointToCoordinate({
					x: pt[0] + mapOffset[0],
					y: pt[1] + mapOffset[1],
				});
				return [data.x, data.y];
			}),
			(CoordSystem.prototype.getViewRect = function getViewRect() {
				var size = map.getSize();
				return new this._echarts.graphic.BoundingRect(
					0,
					0,
					size.width,
					size.height
				);
			}),
			(CoordSystem.prototype.getRoamTransform = function getRoamTransform() {
				return this._echarts.matrix.create();
			});
		console.log("CoordSystem", CoordSystem);
		return CoordSystem;
	}

	loadData() {
		const res = new dataConfig().option;

		if (res) {
			var data = res.locations;
			var geoCoordMap = res.coordinates;
			var convertData = function (data) {
				var res = [];
				for (var i = 0; i < data.length; i++) {
					var geoCoord = geoCoordMap[data[i].name];
					if (geoCoord) {
						res.push({
							name: data[i].name,
							value: geoCoord.concat(data[i].value),
						});
					}
				}
				return res;
			};
			this._ecOptions = {
				title: {
					text: "全国主要城市空气质量",
					subtext: "",
					sublink: "",
					left: "center",
					textStyle: {
						color: "red",
					},
				},
				tooltip: {
					trigger: "item",
				},
				openlayers: {},
				legend: {
					orient: "vertical",
					y: "top",
					x: "right",
					data: ["pm2.5"],
					textStyle: {
						color: "red",
					},
				},
				series: [
					{
						name: "pm2.5",
						type: "scatter",
						data: this.mapData(
							convertData(data),
							15 - this.ol.getView().getZoom()
						),
						symbolSize: function (val) {
							return val[2] / 10;
						},
						label: {
							normal: {
								formatter: "{b}",
								position: "right",
								show: true,
							},
							emphasis: {
								show: true,
							},
						},
						itemStyle: {
							normal: {
								color: "#800080",
							},
						},
					},
					{
						name: "Top 5",
						type: "effectScatter",
						data: convertData(
							data
								.sort(function (a, b) {
									return b.value - a.value;
								})
								.slice(0, 6)
						),
						symbolSize: function (val) {
							return val[2] / 10;
						},
						showEffectOn: "render",
						rippleEffect: {
							brushType: "stroke",
						},
						hoverAnimation: true,
						label: {
							normal: {
								formatter: "{b}",
								position: "right",
								show: true,
							},
						},
						itemStyle: {
							normal: {
								color: "#800080",
								shadowBlur: 10,
								shadowColor: "#800080",
							},
						},
						zlevel: 1,
					},
				],
			};
			// console.log("this._ecOptions", this._ecOptions);
		}
	}
	onMoveEnd(e) {
		// console.log("e", e);
		// console.log("this._ecOptions.series", this._ecOptions.series);
		// this.loadData();
		if (e.type === "postrender") {
			this._ec.setOption(this._ecOptions, false);
		}

		if (e.type === "change:resolution") {
			this.changeZoomChange();
		}
	}

	// 地图数据点聚合
	mapData(list, distance) {
		// console.log("list", list);
		// distance 判断聚合点数值 可以自行定义
		let arrMaplist = [],
			lngIndex = true,
			latIndex = 1;
		// 声明一个数组，包含与原始数据一样长度的n个数组
		for (let i = 0; i < list.length; i++) {
			arrMaplist.push([]);
		}
		// 遍历原始数据
		for (let i = 0; i < list.length; i++) {
			// 存储内层遍历起始数据
			latIndex = latIndex == i ? i + 1 : latIndex;

			for (let j = latIndex; j < list.length; j++) {
				// 对比当前数据与下一个数据 是否属于同一个点聚合
				if (
					Math.abs(list[i].value[0] - list[j].value[0]) <= distance &&
					Math.abs(list[i].value[1] - list[j].value[1]) <= distance
				) {
					// 遍历查看是否存在已有聚合点
					arrMaplist.forEach((ele) => {
						if (ele.length > 0) {
							// 有数据
							ele.forEach((val) => {
								// 且数据中包含当前元素 将下一元素放进去
								if (
									val.value[0] == list[i].value[0] &&
									val.value[1] == list[i].value[1]
								) {
									ele.push(list[j]);
									lngIndex = true;
								} else {
									lngIndex = false; // 不包含
								}
							});
						} else {
							lngIndex = false; // 不包含
						}
					});
					if (!lngIndex) {
						arrMaplist[i].push(list[j]); // 新增聚合点
					}
					latIndex = j + 1;
				}
			}
		}
		// 聚合点总数
		arrMaplist.forEach((item, index) => {
			if (item.length != 0) {
				list[index].total = item.length;
			}
		});
		// 删除list 里面的对应的多余数据，只保留第一条
		arrMaplist.forEach((item) => {
			item.forEach((ele) => {
				let inde = list.indexOf(ele);
				list.splice(inde, 1);
			});
		});

		return list;
	}

	changeZoomChange() {
		// const that = this;
		this.loadData();
		console.log("1111", this._ecOptions.series[0].data);
		that._ec.setOption(this._ecOptions, false);
	}
	changeZoomChange = this.debounce(this.changeZoomChange.bind(this), 500);
	debounce(func, delay) {
		let timerId;
		return function () {
			clearTimeout(timerId);
			timerId = setTimeout(func, delay);
		};
	}
}
